package com.nx.platform.es.bean.modle.sort;

import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class GeoDistanceSortHandler implements SortFieldHandler {

    @Override
    public SortBuilder<?> handle(ImmutableMap<String, ?> fieldConfig, Map<String, Object> params, SortOrder sortOrder) {
        double lon = MapUtils.getDoubleValue(params, "lon");
        double lat = MapUtils.getDoubleValue(params, "lat");
        if (Double.doubleToLongBits(lon) == 0 && Double.doubleToLongBits(lat) == 0) {
            return null;
        }
        Object order = MapUtils.getObject(fieldConfig, "order");
        String fieldName = MapUtils.getString(fieldConfig, "fieldName");
        return SortBuilders.geoDistanceSort(fieldName, lat, lon)
                .order((order instanceof SortOrder) ? (SortOrder) order : SortOrder.ASC);
    }

}
